<template>
  <div style="display: flex; height: 100%; flex: 1;">
    <HierarchyList :pagination="pagination" :columns="columns" :load-data="loadData"
                   ref="refHiRole" :search-form="searchItems" :create-label="'新增角色'"
                   :add-item="addRole" />
    <EditDialog ref="refEditDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>
    <LevelSelectorDialog ref="refLevelDlg" :load="onLoadMoveRole" :title="'移动角色'" :tag="'角色'" :level-mode="true"
                         :mode="'MOVE'" :root-item="{id:'', name:'角色列表'}" :finish-select="onFinishMove" />
  </div>
</template>

<script setup lang="ts">

import {onMounted, reactive, ref} from "vue";

import {buildSearchForms} from "@/data/PageData";
import {msgError, msgInfo, showInfo} from "@/utils/InfoUtil";
import {buildAsset} from "@/utils/DataUtil";

import EditDialog from "@/components/common/EditDialog.vue";
import HierarchyList from "@/widget/list/HierarchyList.vue";
import LevelSelectorDialog from "@/widget/selector/LevelSelectorDialog.vue";
import {useTerminal} from "@/utils/UseTerminal";
import {useCurrent} from "@/utils/UseCurrentFunc";
import {currentNames, TYPES} from "@/stores/conf";
import {useAssetOp} from "@/utils/UseAssetOp";
import {getStateOptions, getStateTag, getStateText, handleResult} from "@/utils/SystemUtil";

const props = withDefaults(defineProps<{
  entry: any,
  product?: boolean,
  fromDetail?: boolean,
  moveRole?: any,
  loadMoveRole?: any,
  clickCurrent?: any,
}>(), {});

const refHiRole = ref();
const refEditDlg = ref();
const refLevelDlg = ref();

const {updateCurrent, current} = useCurrent(currentNames.ROLE);
const {doLoadAsset, doSaveAsset, doDeleteAsset, doMoveAsset, doLoadMoveAsset} = useAssetOp(props.entry);

const currentItem = ref();
const {productCode, onTerminal} = useTerminal(currentNames.ROLE);

const searchItems = ref(buildSearchForms('角色', {
  show: props.product,
  onChanged: onTerminal,
}));

const rules = reactive({
  name: [{required: true, message: '请输入角色名称', trigger: ['blur']},],
})

const getTargetId = () => {
  return '';
}

const loadData = async (params: any) => {
  const id: string = current().id;

  if (props.fromDetail && !id) {
    return;
  }

  if (!props.fromDetail && id) {
    return;
  }

  const result = await doLoadAsset(getTargetId(), TYPES.ROLE, {
    parentId: current().id,
    ...params
  });
  if (result && result.code === 0) {
    msgInfo('加载角色信息成功!');
    handleResult(result.data, ['$comment']);
  } else {
    msgError(result ? result.message : '加载角色信息失败！');
  }

  return result;
}

const refresh = () => {
  refHiRole.value?.refresh({
    ...current(),
  })
}

const onSubmit = async (item: Record<string, any>) => {
  let assetInfo = buildAsset(item, 'ROLE', {
    $comment: item.$comment || ''
  });

  assetInfo.classify = "TREE";

  const result = await doSaveAsset(getTargetId(), assetInfo);
  if (result && result.code === 0) {
    msgInfo('保存角色信息成功!');
    setTimeout(() => refresh(),300);
  } else {
    msgError(result ? result.message : '保存角色信息失败！');
  }

  return result;
}

const onFinishMove = async (item: any) => {
  const p: any = {
    assetId: currentItem.value.id,
    assetType: TYPES.ROLE,
    parentId: item.id,
  };
  let result: any;

  if (props.moveRole) {
    result = await props.moveRole(p);
  } else {
    result = await doMoveAsset(getTargetId(), p);
  }

  if (result && result.code == 0) {
    refresh();
  }
}

const onLoadMoveRole = async (params: any) => {
  let result: any;
  const p: any = {
    assetId: currentItem.value.id,
    assetType: TYPES.ROLE,
    productCode: productCode(),
    ...params,
  };

  if (props.loadMoveRole) {
    result = await props.loadMoveRole(p);
  } else {
    result = await doLoadMoveAsset(getTargetId(), p);
  }

  return result;
}

const newRole = () => {
  return {
    state: 1,
    type: TYPES.ROLE,
  };
}

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const columns = ref([
  {
    id: 'id',
    name: '标识',
    hideCol: true,
    show: false,
    canEdit: false,
  },
  {
    id: 'parentId',
    name: '父角色',
    hideCol: true,
    type: 'tree',
    readOnly: true,
    canEdit: false,
    treeKey: 'parentName'
  },
  {
    id: 'name',
    name: '角色名称',
    show: true,
    action: (data: any, row: any) => {
      updateCurrent({type: TYPES.ROLE, ...row});
    }
  },
  {
    id: 'code',
    name: '角色码',
    show: true,
    inputCheck: (row: any) => {
      row.code = row.code.replace(/[^\w\.\/:=|<>+-_%&*#()]/ig,'');
      if (row.code.length > 31) {
        row.code = row.code.substring(0, 31);
      }
    }
  },
  {
    id: 'state',
    name: '状态',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => { return getStateTag(tag); },
    tagText: (tag: number) => { return getStateText(tag); },
    options: getStateOptions()
  },
  {
    id: '$comment',
    name: '描述',
    show: true,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: true,
    canEdit: false,
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    hideCol: true,
    fixed: 'right',
    canEdit: false,
    operations: [
      {
        name: '新增子角色',
        callback: (data: any, row: any, index: number) => {
          const parent = row;

          currentItem.value = newRole();
          currentItem.value.disabled = true;
          currentItem.value.parentId = parent.id;
          currentItem.value.treeData = [
            {
              value: parent.id,
              label: parent.name,
            }
          ]
          refEditDlg.value?.editAdd('新增角色', currentItem.value);
        }
      },
      {
        name: '编辑',
        iconType: 'primary',
        callback: (data: any, row: any, index: number) => {
          currentItem.value = row;
          refEditDlg.value?.editUpdate('编辑角色', row);
        }
      },
      {
        name: '移动',
        iconType: 'primary',
        callback: (data: any, row: any, index: number) => {
          currentItem.value = row;
          refLevelDlg.value?.select();
          refLevelDlg.value?.updateTitle('移动角色 ' + row.name);
        }
      },
      {
        type: 'confirm',
        name: '删除',
        confirm: async (data: any, row: any, index: number) => {
          if (row.children && row.children.length != 0) {
            showInfo('请先删除角色子角色！');
          } else {
            const result = await doDeleteAsset(getTargetId(), row);
            if (result.code === 0) {
              msgInfo('删除角色成功！');
              refresh();
            } else {
              msgError(result.message ? result.message : '删除角色失败！');
            }
          }

        },
        cancel: (data: any, index: number) => {
          const row = data[index];
        }
      }
    ]
  }
]);

const addRole = () => {
  currentItem.value = newRole();
  currentItem.value.parentId = current().id;
  refEditDlg.value?.editAdd('新增角色', currentItem.value);
}

onMounted(() => {

})

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
